<?php
namespace App\Http\Controllers\Service;
use App\Common\ApiData;
use Storage;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Excel;



class UploadController extends Controller{

    /*
     * 保存文件
     * */
    public function upload_file(Request $request){

        $fileData   = $request->input('fileData');
        $fileName   = $request->input('fileName');
        $apiData    = new ApiData();
        $info       = explode('.',$fileName);
        $path       = public_path('/');
        $filePath   = "uploads/uploads/".create_member_number().".".$info[1];
        $path       = $path.$filePath;
        $fileData = preg_replace('/^data:\w*\/*\w*\.*\w*\-*\w*;base64,/','',$fileData);

        $fileData = base64_decode($fileData);
        $result = file_put_contents($path,$fileData);

        if($result){
            $apiData->code  = 200;
            $apiData->message   = "上传成功";
            $apiData->set_data('path',$filePath);
        }else{
            $apiData->code  = 404;
            $apiData->message   = "上传失败";
        }
        return $apiData->send();
    }


    public function read_excel(Request $request){
        $file = $request->input('file');
        $file = public_path("/").$file;
        $apiData = new ApiData();
        if(!file_exists($file)){
            $apiData->message = "文件不存在";
            $apiData->code = 400;
            return $apiData->send();
        }

        $GLOBALS['data']   = [];
        Excel::load($file,function($reader){
            $GLOBALS['data']  = $reader->all();
        });
        $apiData->message = "获取成功";
        $apiData->code  = 200;
        $apiData->set_data('users',$GLOBALS['data']);
        return $apiData->send();
    }



    /**
     * 保存编辑器图片
     * */
    public function save_edit_file(Request $request)
    {
        $dir        = "uploads/".date('Y')."/".date('m')."/".date('d');
        $storyPath  = public_path($dir);

        if(!file_exists($storyPath))
        {
            //mkdir($storyPath,true);
            mk_dir($storyPath);
        }
        $images = [];
        foreach($_FILES as $key => $file)
        {
            $filename   = $file['name'];
            $extend     = pathinfo($filename);
            $type       = strtolower($extend["extension"]);
            $newFile    = time().rand(1000,9000).".".$type;

            $tempFile   = $file['tmp_name'];
            move_uploaded_file($tempFile,$storyPath."/".$newFile);
            array_push($images,"/".$dir."/".$newFile);
        }

        $data = ['errno'=>0,'data'=>$images];

        echo json_encode($data);
    }

    
}